SQL ORDER BY Clause

    If we want to display or fetch data from the table in a stored manner then we have to use the SQL ORDER BY clause which can sort the data in ascending or descending order. By default, if we fetch the data, the SQL show it in Ascending order but using the ORDER BY clause and ASC and DESC operators we can sort data in ascending and descending order.

    ORDER BY syntax

    Follow this syntax to use the ORDER BY clause:

    SELECT column_name 
    FROM table_name 
    WHERE [condition] 
    ORDER BY [column_name_n] [ASC | DESC];

    The column name which is mentioned along with the ORDER BY command becomes the base reference on which we want to sort the data. We can also pass more than one column name to the ORDER BY clause. Example For this example consider this table of students:

    +------+--------+------+--------+-------+
    | id   | name   | age  | grades | marks |
    +------+--------+------+--------+-------+
    |    1 | Luffy  |   16 | A      |   970 |
    |    2 | Naruto |   18 | A      |   960 |
    |    3 | Zoro   |   20 | A      |   940 |
    |    4 | Sanji  |   21 | B      |   899 |
    |    5 | Nami   |   17 | B      |   896 |
    |    6 | Robin  | NULL | B      |   860 |
    +------+--------+------+--------+-------+

    Query: Show all the students name and sort them according to their age in ascending order.

    SELECT name
    FROM students
    ORDER BY age ASC;
    

    Output

    +--------+
    | name   |
    +--------+
    | Robin  |
    | Luffy  |
    | Nami   |
    | Naruto |
    | Zoro   |
    | Sanji  |
    +--------+

    Query: Show students name, marks and their age, and sort them descending order according to their marks.

    SELECT name, age, marks
    FROM students
    ORDER BY marks DESC;
    

    Output

    +--------+------+-------+
    | name   | age  | marks |
    +--------+------+-------+
    | Luffy  |   16 |   970 |
    | Naruto |   18 |   960 |
    | Zoro   |   20 |   940 |
    | Sanji  |   21 |   899 |
    | Nami   |   17 |   896 |
    | Robin  | NULL |   860 |
    +--------+------+-------+

    Summary

    • ORDER BY clause is used to sort the data.
    • By default Order BY sort data in ascending order.
    • Using ORDER by we can sort data in ascending as well as in Descending order.
    • ASC operator stands for ascending.
    • DESC stand for Descending.

    People are also reading: